package com.fh.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpAddressUtils {
	public static final String INTRANET_IP = getIntranetIp(); // ����IP
    public static final String INTERNET_IP = getInternetIp(); // ����IP
    public static final byte[] INTERNET_IP_BYTES = getInternetIpBytes();//����ip�ֽ�����
    public static final byte[] INTRANET_IP_BYTES = getIntranetIpBytes(); // ����IP�ֽ�����

   // private IpAddressUtils(){}

    /**
     * �������IP
     * @return ����IP
     */
    private static String getIntranetIp(){
        try{
            return InetAddress.getLocalHost().getHostAddress();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * �������IP
     * @return ����IP
     */
    private static String getInternetIp(){
        try{
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration<InetAddress> addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(INTRANET_IP))
                    {
                        return ip.getHostAddress();
                    }
                }
            }

            // ���û������IP���ͷ�������IP
            return INTRANET_IP;
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * �������IP
     * @return ����IP
     */
    private static byte[] getInternetIpBytes(){
        return ipv4Address2BinaryArray(getInternetIp());
    }

    /**
     * ��ȡ����ip
     * @return
     */
    private static byte[] getIntranetIpBytes() {
        return ipv4Address2BinaryArray(getIntranetIp());
    }

    /**
     * ����������ʮ���Ʒֶθ�ʽ��ʾ��ipv4��ַ�ַ���ת�����ֽ�����
     * @param ipAdd
     * @return
     */
    private static byte[] ipv4Address2BinaryArray(String ipAdd){
        byte[] binIP = new byte[4];
        String[] strs = ipAdd.split("\\.");
        for(int i=0;i<strs.length;i++){
            binIP[i] = (byte) Integer.parseInt(strs[i]);
        }
        return binIP;
    }

    public static void main(String[] args) {
        String internetIp = getInternetIp();
        System.out.println(internetIp);
        String intranetIp = getIntranetIp();

        System.out.println(intranetIp);
    }


}
